const path = require('path')
const Html = require('html-webpack-plugin')
const autoprefix = require('autoprefixer')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
const packageConfig = require('./package.json')
const notifier = require('node-notifier')
const debug = process.env.NODE_ENV === 'dev'

module.exports = {
    mode: debug ? 'development' : 'production',
    entry: {
        app: './html/index.js'
    },
    output: {
        path: path.join(__dirname, './dist'),
        filename: "[name].[hash].js"
    },
    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            'vue$': 'vue/dist/vue.js',
            '~': __dirname
        }
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.vue$/,
                use: 'vue-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ['css-loader?modules&localIdentName=[local]-[hash:base64:5]', 'postcss-loader']
                })
            }
        ]
    },
    plugins: [
        new Html({
            template: './html/index.html',
            inject: 'body'
        }),
        autoprefix,
        new ExtractTextPlugin({
            filename: '[name].[hash:8].css'
        }),
        new VueLoaderPlugin()
    ],
}
if (debug) {
    module.exports.devServer = {
        host: 'localhost',
        port: 10123,
        contentBase: './dist',
        inline: true,
        quiet: true,
        clientLogLevel: 'warning',
        overlay: {
            warnings: true,
            errors: true
        }
    }
    module.exports.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
            messages: [`Your application is running here: http://${module.exports.devServer.host}:${module.exports.devServer.port}`],
        },
        onErrors: (severity, errors) => {
            if (severity !== 'error') return

            const error = errors[0]
            const filename = error.file && error.file.split('!').pop()

            notifier.notify({
                title: packageConfig.name,
                message: severity + ': ' + error.name,
                subtitle: filename || '',
                icon: path.join(__dirname, 'logo.png')
            })
        }
    }))
}
